package api

import (
	"encoding/json"
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"hhos-mdijounery-server/api/request"
	"hhos-mdijounery-server/api/response"
	"hhos-mdijounery-server/dao"
	global2 "hhos-mdijounery-server/global"
	"hhos-mdijounery-server/service"
	"io/ioutil"
	"net/http"
	"strconv"
	"strings"
)

var (
	global = global2.ReadConfig()
	dsn    = fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", global.Mysql.User, global.Mysql.Password, global.Mysql.Host, global.Mysql.Port, global.Mysql.DbName)
	db, _  = gorm.Open(mysql.Open(dsn), &gorm.Config{})
)

// Callback 回调
func Callback(w http.ResponseWriter, r *http.Request) {

	var params request.CallbackRequest

	// 读取请求数据
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		response.ResponseFailMessage(w, "Failed to read request body")
		return
	}
	// 将数据绑定到params
	err = json.Unmarshal(body, &params)
	if err != nil {
		response.ResponseFailMessage(w, "Failed to parse JSON")
		return
	}

	// 判断进度顺序
	if params.TaskProgress != "" {
		params.TaskProgressInt, err = strconv.Atoi(strings.Trim(params.TaskProgress, "%"))
		if err != nil {
			response.ResponseFailMessage(w, err.Error())
			return
		}
	}

	midjourneyDao := dao.NewMidjourneyDAO(db)
	midjourneyService := service.NewMidjourney(midjourneyDao, nil)
	err = midjourneyService.Callback(r.Context(), &params)
	if err != nil {
		response.ResponseFailMessage(w, err.Error())
		return
	}

	response.ResponseOk(w)
}
